import 'dart:convert';


import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:szwf/utils/common_toast.dart';
import '../utils/dio_http.dart';
import './Index.dart';
import 'dart:async';

import 'end.dart';

// class Tag extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return ;
//   }
// }

class Tag extends StatefulWidget {
  const Tag({Key key}) : super(key: key);

  @override
  _TagState createState() => _TagState();
}

class _TagState extends State<Tag> {
  List _tagList = List(4);
  int _index = 0;
  String companyId = '';
  String fid = '';
  String wid = '';
  String sid = '';
  String bid = '';
  String time = '';

  // String weight = '';

  @override
  void initState() {
    super.initState();
    updataTime();

    getTag().then((value) async {
      setState(() {
        _tagList = json.decode(value.toString())['ret'];
      });

      const url = '/wfgl/ingredient/getList';
      var params = {
        "companyId": this.companyId,
        'wasteId': this.wid,
        'beenDeleted': 0
      };
      var res = await DioHttp.of(context).post(url, params);
      var resString = json.decode(res.toString());

      var dataList = [];
      for (var i = 0; i < resString['ret'].length; i++) {
        var id = resString['ret'][i]['id'].toString();
        var name = resString['ret'][i]['name'];
        var obj = {"id": id, "name": name};
        dataList.add(obj);
      }

      var _obj = {
        "dataList": dataList,
        "name": "主要成分",
        "checked": false,
        "checkedItem": "",
        "checkedId": ""
      };

      var arr = _tagList;

      arr.insert(1, _obj);
      setState(() {
        _tagList = arr;
      });
    });
  }

  updataTime() {
    const timeout = const Duration(seconds: 1);
    Timer(timeout, () {
      //到时回调
      var nowTime = DateTime.now();
      var span = Duration(hours: 8);
      nowTime = nowTime.add(span);
      setState(() {
        this.time = nowTime.toString().substring(0, 19);
      });
      updataTime();
    });
  }

  Future getTag() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var cid = prefs.getString('companyId');
    this.setState(() {
      companyId = cid;
    });
    print(cid);

    const url = '/wfgl/hazardouswaste/findThreeList';
    var params = {
      "companyId": cid,
    };
    var res = await DioHttp.of(context).post(url, params);

    return res;
  }

  submit(a) async {
    const url = '/wfgl/qrcode/insertSelective';
    var params = {
      "companyId": companyId,
      "assemblyLineId": fid,
      "ingredientId": sid,
      "nameId": wid,
      "packTypeId": bid,
      "weight": a
    };
    print('submit params: ');
    print(params);

    var res = await DioHttp.of(context).post(url, params);
    var resString = json.decode(res.toString());

    if (resString['rc'] == 0) {
      print(resString);
      CommonToast.showToast('操作成功,正在生产二维码!');
      final prefs = await SharedPreferences.getInstance();
      var qrCode = resString['ret']['qrCode'].toString();
      var qrNumber = resString['ret']['qrNumber'].toString();
      prefs.setString('qrCode', qrCode);
      prefs.setString('qrNumber', qrNumber);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (BuildContext context) {
          return EndPage();
        },
        settings: RouteSettings(
          arguments: {"qrNumber": qrNumber},
        ), // 传参
        fullscreenDialog: true,
      ));
    }else{
      CommonToast.showToast(resString['err']);
    }
  }

  Widget _tagListWidget() {
    return Container(
        height: 330,
        padding: EdgeInsets.all(30),
        child: ListView(
          children: _renderList(),
        ));
  }

  handleChecked() {

    var count = 0;
    for (var i = 0; i < _tagList.length; i++) {
      if (_tagList[i]['checkedItem'].length > 0) {
        ++count;
      }
    }

    return count;
  }

  _renderList() {
    List<Widget> tmp = [];

    for (var i = 0; i < _tagList[_index]['dataList'].length; i++) {
      tmp.add(InkWell(
        onTap: () {

          if (_index == 0) {
            setState(() {
              wid = _tagList[_index]['dataList'][i]['id'].toString();
            });
          }
          if (_index == 1) {
            setState(() {
              sid = _tagList[_index]['dataList'][i]['id'].toString();
            });
          }
          if (_index == 2) {
            setState(() {
              bid = _tagList[_index]['dataList'][i]['id'].toString();
            });
          }
          if (_index == 3) {
            setState(() {
              fid = _tagList[_index]['dataList'][i]['id'].toString();
            });
          }
          setState(() {
            _tagList[_index]['checked'] = true;
            _tagList[_index]['checkedId'] = _tagList[_index]['dataList'][i]['checkedId'].toString();
            _tagList[_index]['checkedItem'] = _tagList[_index]['dataList'][i]['name'];
          });
          // var a = this._tagList[_index]['dataList'][i]['id'];
          // a = a.toString()

        },
        child: Wrap(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  _tagList[_index]['dataList'][i]['name'],
                  style: TextStyle(
                    fontSize: 16.0,
                  ),
                ),
                Text(
                    _tagList[_index]["checked"] &&
                        _tagList[_index]["checkedItem"] ==
                            _tagList[_index]['dataList'][i]['name']
                        ? '√'
                        : '',
                    style: TextStyle(
                      fontSize: 20.0,
                      color: Colors.blue,
                    )),
              ],
            ),
            Divider()
          ],
        ),
      ));
    }

    return tmp;
  }

  @override
  Widget build(BuildContext context) {
    Map weight = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        title: Text('苏州正济药业有限公司'),
        actions: <Widget>[
          Container(
            padding: EdgeInsets.fromLTRB(0, 15, 10, 10),
            child: Text('$time',
                style: TextStyle(
                  fontSize: 20.0,
                  // color: Colors.blue,
                )),
          )
        ],
      ),
      body: Container(
        child: Stack(
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                    flex: 3,
                    child: Stack(
                      children: <Widget>[
                        Container(
                            padding: EdgeInsets.fromLTRB(20, 20, 20, 20),
//                    height: double.infinity,
                            decoration: BoxDecoration(
                                color: Colors.white10,
                                borderRadius:
                                BorderRadius.all(Radius.circular(10.0))),
                            child: ListView.builder(
                                itemCount: 5,
                                // ignore: missing_return
                                itemBuilder: (context, index) {
                                  if (index == 0) {
                                    return Wrap(
                                      children: <Widget>[
                                        ListTile(
                                          leading: Image.asset(
                                            'images/icons/重量.png',
                                          ),
                                          trailing: Text("${weight['weight']}"),
                                          title: Text(
                                            "称重重量:",
                                            style: TextStyle(fontSize: 18.0),
                                          ),
                                        ),
                                        // ignore: dead_code
                                        Divider()
                                      ],
                                    );
                                  }
                                  if (index == 1) {
                                    return Wrap(
                                      children: <Widget>[
                                        ListTile(
                                          leading: Image.asset(
                                              'images/icons/危废.png'),
                                          trailing: Text(
                                              '${this._tagList[0]['checkedItem']}'),
                                          title: Text(
                                            "危废名称:",
                                            style: TextStyle(fontSize: 18.0),
                                          ),
                                        ),
                                        // ignore: dead_code
                                        Divider()
                                      ],
                                    );
                                  }
                                  if (index == 2) {
                                    return Wrap(
                                      children: <Widget>[
                                        ListTile(
                                          leading: Image.asset(
                                              'images/icons/成分.png'),
                                          trailing: Text(this._tagList.length >
                                              3
                                              ? '${this._tagList[1]['checkedItem']}'
                                              : ''),
                                          title: Text(
                                            "主要成分:",
                                            style: TextStyle(fontSize: 18.0),
                                          ),
                                        ),
                                        Divider()
                                      ],
                                    );
                                  }
                                  if (index == 3) {
                                    return Wrap(
                                      children: <Widget>[
                                        ListTile(
                                          leading: Image.asset(
                                              'images/icons/生产线.png'),
                                          trailing: Text(
                                              '${this._tagList[2]['checkedItem']}'),
                                          title: Text(
                                            "生产线:",
                                            style: TextStyle(fontSize: 18.0),
                                          ),
                                        ),
                                        Divider()
                                      ],
                                    );
                                  }
                                  if (index == 4) {
                                    return Wrap(
                                      children: <Widget>[
                                        ListTile(
                                          leading: Image.asset(
                                              'images/icons/包装.png'),
                                          trailing: Text(
                                            _tagList[3]['checkedItem'],
                                          ),
                                          title: Text(
                                            "包装类型:",
                                            style: TextStyle(fontSize: 18.0),
                                          ),
                                        )
                                      ],
                                    );
                                    // ignore: dead_code
                                    SizedBox(
                                      height: 40,
                                    );
                                  }
                                })),
                        Positioned(
                          width: 200,
                          bottom: 20,
                          left: 200,
                          child: RaisedButton(
                            color:
                            handleChecked() == 4 && weight['weight'] != ''
                                ? Color.fromRGBO(0, 191, 255, 1)
                                : Color.fromRGBO(142, 193, 244, 1),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20),
                            ),
                            textColor: Colors.white,
                            child: Text('完成'),
                            onPressed: () {
                              if (handleChecked() == 4 &&
                                  weight['weight'] != '') {
                                var a = weight['weight'];
                                submit(a);
                              } else {
                                return null;
                              }
                            },
                          ),
                        )
                      ],
                    )),
                Expanded(
                  flex: 2,
                  child: Stack(
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
                        decoration: BoxDecoration(
                          color: Colors.white10,
                          borderRadius:
                          BorderRadius.all(Radius.circular(10.0),
                          ),
                        ),
                        child: Container(
                            height: double.infinity,
                            child: Column(
                              children: <Widget>[
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  children: <Widget>[
                                    IconButton(
                                        icon: Icon(
                                          Icons.chevron_left,
                                          size: 38,
                                        ),
                                        onPressed: () {
                                          if (_index >= 0) {
                                            --_index;
                                          }
                                        }),
                                    Text(
                                      _tagList[_index]['name'],
                                      style: TextStyle(
                                        fontSize: 26,
                                      ),
                                    ),
                                  ],
                                ),
                                this._tagListWidget(),
                              ],
                            )),
                      ),
                      Positioned(
                        left: 60,
                        bottom: 20,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            RaisedButton(
                              color: _index != 0 ? Colors.blue : Color.fromRGBO(224, 224, 224, 1),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20),
                              ),
                              textColor: Colors.white,
                              child: Text('上一步'),
                              onPressed: () {
                                if (_index > 0) {
                                  setState(() {
                                    _index = --_index;
                                  });
                                  if (_index == 0) {
                                    List arr = _tagList;
                                    arr.removeLast();
                                    setState(() {
                                      _tagList = arr;
                                    });
                                  }
                                }
                              },
                            ),
                            SizedBox(
                              width: 30,
                            ),
                            RaisedButton(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(20),
                              ),
                              textColor: Colors.white,
                              child: Text('下一步'),
                              color: _tagList.length - 1 > _index
                                  ? Colors.blue
                                  : Color.fromRGBO(224, 224, 224, 1),
                              onPressed: () {
                                if (_tagList.length - 1 > _index) {
                                  _index = _index + 1;
                                }
                              },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
}
